//
//  NSDate+Extension.swift
//  WeiBo
//
//  Created by 韩俊 on 15/12/16.
//  Copyright © 2015年 HanJun. All rights reserved.
//

import Foundation

extension NSDate {
    
    class func sinaDate(createStr:String) -> NSDate? {
        
        let dateFormatter = NSDateFormatter()
        //指定格式
        dateFormatter.dateFormat = "EEE MM dd HH:mm:ss z yyyy"
        //指定本地化信息
        dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
        //微博的创建时间(NSDate)
        let createDate = dateFormatter.dateFromString(createStr)
        
        return createDate
    }
    
    var sinaDateString: String {
        
        let dateFormatter = NSDateFormatter()
        dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
        let calendar = NSCalendar.currentCalendar()
        
        
        if isThisYear(self) {
            dateFormatter.dateFormat = "是今年"
            if calendar.isDateInToday(self){
                //是今天
                //求处当前时间与微博创建时间的差
                //let currentDate = NSDate()
                let result = -self.timeIntervalSinceNow
                
                if result < 60 {
                    return "刚刚"
                    
                }else if result < 60*60 {
                    return "\(Int(result) / 60)分钟前"
                    
                }else{
                    return "\(Int(result) / 60 / 60)小时前"
                    
                }
                
            }else if calendar.isDateInYesterday(self){
                //是昨天
                dateFormatter.dateFormat = "昨天 HH:mm"
                
            }else{
                //其他
                dateFormatter.dateFormat = "MM-dd HH:mm"
            }
            
        }else{
            //不是今年
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
            
        }
        
        
        return dateFormatter.stringFromDate(self)

    }
    
    
    //判断传入的date与当前时间是否是同一年
    private func isThisYear(date:NSDate) -> Bool {
        
        let currentDate = NSDate()
        
        let dateFormatter = NSDateFormatter()
        //指定格式
        dateFormatter.dateFormat = "yyyy"
        //指定本地化信息
        dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
        
        let dateStr = dateFormatter.stringFromDate(date)
        let currentDateStr = dateFormatter.stringFromDate(currentDate)
        
        return (dateStr as NSString).isEqualToString(currentDateStr)
        
    }

    
}